import { createRouter, createWebHistory } from 'vue-router'

// 用户端路由
import userRoutes from './modules/user'
// 门店端路由
import storeRoutes from './modules/store'
// 管理端路由
import adminRoutes from './modules/admin'

// 公共路由
const publicRoutes = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/login/index.vue'),
    meta: { title: '登录' }
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('../views/login/register.vue'),
    meta: { title: '注册' }
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: () => import('../views/error/404.vue'),
    meta: { title: '404' }
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes: [
    ...publicRoutes,
    userRoutes,
    storeRoutes,
    adminRoutes
  ]
})

// 路由守卫
router.beforeEach((to, from, next) => {
  // 设置页面标题
  document.title = to.meta.title || '药店管理系统'
  
  // 判断是否需要登录权限
  if (to.meta.requiresAuth) {
    // 从localStorage获取token
    const token = localStorage.getItem('token')
    // 从localStorage获取用户角色
    const role = localStorage.getItem('role')
    
    if (!token) {
      // 未登录，跳转到登录页
      next({ name: 'Login' })
    } else {
      // 根据角色判断是否有权限访问
      if (to.meta.roles && to.meta.roles.includes(role)) {
        next()
      } else if (to.path.startsWith('/user') && role === 'user') {
        next()
      } else if (to.path.startsWith('/store') && role === 'store') {
        next()
      } else if (to.path.startsWith('/admin') && role === 'admin') {
        next()
      } else {
        // 无权限访问，跳转到对应角色的首页
        if (role === 'user') {
          next({ path: '/user' })
        } else if (role === 'store') {
          next({ path: '/store' })
        } else if (role === 'admin') {
          next({ path: '/admin' })
        } else {
          next({ name: 'Login' })
        }
      }
    }
  } else {
    next()
  }
})

export default router